//
//  CZEmoticonViewCell.swift
//  微博
//
//  Created by 霸气的刘吉庆 on 16/4/28.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit

class CZEmoticonViewCell: UICollectionViewCell {
    //定义一个属性,方便外面看的传值
    var emotiocons: [CZEmoticonModel]?{
        //赋值的时候,设置button里面的数据,顺便怎么呢,顺便需要考虑cell的重用
        didSet{
            
//            print(emotiocons)
            guard let emotioconModel = emotiocons else{
                return
            }
            //首先遍历按钮的数组,为了防止重用,先把里面的按钮都都隐藏,设置的时候在把他的button
            for value in self.emoticonsArray{
                value.hidden = true
            }
            
            //这个emoticonModel是一个模型数据
            for (index,value) in emotioconModel.enumerate(){
                let button = emoticonsArray[index]
                button.emoticonModel = value
                //设置button的状态为显示
                button.hidden = false
                //设置表情的image

//                print(value.folderName)
//                print(value.png)
                
                
//                print(image)
//                //设置button里面的内容
                
                //判断是emoji表情还是图片表情
//                if value.type == "1" {
//                    //如果是1 代表的是emoji表情,直接设置字体
//                    button.setTitle(((value.code!) as NSString).emoji(), forState: .Normal)
//                    button.setImage(nil, forState: .Normal)
//                    
//                }else{
//                    
//                    //代表是图片表情
//                    let image = UIImage(named:"\(value.folderName ?? "")/\(value.png ?? "")" , inBundle: CZEmoticonKeyBoardViewModel.sharedViewModel.emoticonBundle, compatibleWithTraitCollection: nil)
//                    button.setImage(image, forState: .Normal)
//                    button.setTitle(nil, forState: .Normal)
//                }
                
                
            }
            
        }
  
    }
    
    //创建一个indexPath测试当前的cell是第几个
    var indexPath: NSIndexPath? {
        didSet{
//            label.text = "第\(indexPath?.section ?? 0)组,第\(indexPath?.item ?? 0)页"
//            label.text = "最近使用的表情"
//            //为0才影藏,不为0不隐藏
//            label.hidden = indexPath?.section != 0
            messageLabel.hidden = indexPath?.section != 0
            
        }
        
    }
    
    private lazy  var emoticonsArray: [CZEmoticonButton] = []
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
      
//        CZEmoticonButton
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //循环添加20个按钮
    private func setupUI(){
       
        //添加label
//        backgroundColor = UIColor.clearColor()
    
//        addSubview(label)
//        //设置约束
//        label.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(self)
//        }
        addSubview(messageLabel)
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-10)
        }
        //添加视图的时候一定要注意先后顺序
        addChildButtons()
        contentView.addSubview(deleteButton)
        //添加手势
        let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
        //添加手势到contentView上
        contentView.addGestureRecognizer(longPress)
        //设施多长事件触发事件
        longPress.minimumPressDuration = 0.25
    }
    
    //长按显示popView的事件
    
    @objc private func longPress(longPress: UILongPressGestureRecognizer){
        //思路,首先判断这个点在什么地方,其次,这个点对应的button,显示内容
        
        //1.取到手指所在的位置
        let location = longPress.locationInView(longPress.view)
        
        //2.找到该位置对应的按钮(方法)
        
        func buttonWithLocation(location: CGPoint)-> CZEmoticonButton? {
            
            for value in emoticonsArray {
                
                if CGRectContainsPoint(value.frame, location) {
                    return value
                }
                
            }
            
            return nil
            
        }
        
        
        
        //3.通过点找到对应的表情按钮
        
        guard let btn = buttonWithLocation(location) else{
            popView.removeFromSuperview()
            return
        }
        
        //4.使用switch判断状态,防止重复添加
        
        switch longPress.state{
         //注意这个case中间的","代表的是或者
        case .Began,.Changed:
            
            //来到这里需要进行判断,如果上一次选中的按钮和这次选中的按钮相同直接return
            //这样可以加快运行的效率
            if popView.emoticonButton == btn.emoticonModel {
                return
            }
            //如果是长按手势的触发和改变,来到这里
            //1.取到最上层的window
            let window = UIApplication.sharedApplication().windows.last!
            //坐标的装换
            //这个方法的含义,将btn转换成window的坐标,如果是btn的superView就需要使用相对的坐标
            
            let rect = btn.superview!.convertRect(btn.frame, toView: window)
            //设置坐标和属性,添加到父view上面
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            
            //给popView里面的属性赋值
            popView.emoticonButton.emoticonModel = btn.emoticonModel
            //添加到view上面
            window.addSubview(popView)
            
            
            
            break
            
        default:
            //这里只需要把button的值设置为nil就行了,为什么会有这种bug,因为第一次点击的时候popView里面已经有值了,而且我们是懒加载的,咯面的popView里面的属性没有改变,所以我们需要进行重新设置
            popView.emoticonButton.emoticonModel = nil
            
            popView.removeFromSuperview()
            
            break
            
            
            
            
            
        }
        
        
        
        
        
        
        
    }
    
    
    
    private func addChildButtons(){
        
        let maxCount = CZEmoticonKeyBoardViewModelEmoticonButtonCount
        for _ in 0..<maxCount{
            //注意这里只是添加按钮,具体的布局要写在layoutSubViews中
            let button = CZEmoticonButton()
            button.addTarget(self, action: "didClickEmoticonsButton:", forControlEvents: .TouchUpInside)
            //设置按钮的背景颜色为随机
//            button.backgroundColor = RandomColor
            //设置按钮中的字体的大小
            button.titleLabel?.font = UIFont.systemFontOfSize(35)
            
            contentView.addSubview(button)
            
            emoticonsArray.append(button)
        }
        
//        print(emoticonsArray)
        
    }
    //表情按钮的单击事件
    @objc private func didClickEmoticonsButton(button: CZEmoticonButton){
//       print(button.emoticonModel?.chs)
        
        //保存最近表情
        //注意需要强行解包
        CZEmoticonKeyBoardViewModel.sharedViewModel.saveRecentEmoticon(button.emoticonModel!)
        
        
        //发送通知,传过去必须是必选值
        NSNotificationCenter.defaultCenter().postNotificationName(CZEmoticonButtonNotification, object: nil, userInfo: ["emoticonModel":button.emoticonModel!])
        
        
        //1.取到上层的window
        let window = UIApplication.sharedApplication().windows.last!
        //出事化一个popVIew
//        let popView = CZEmoticonPopView.popView()
        
        popView.emoticonButton.emoticonModel = button.emoticonModel
        //2.设置popVIew的位置,相对于window
        let rect = button.superview!.convertRect(button.frame, toView: window)
        
        //设置popView的坐标
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        //添加popVIew
        
        window.addSubview(popView)
        
        //设置几秒钟之后消失
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.popView.removeFromSuperview()
        }
        
    }
    //布局20个子view的控件
    override func layoutSubviews() {
        super.layoutSubviews()
        //计算按钮的长度和宽度
        let itemW = self.frame.width / CGFloat(CZEmoticonKeyBoardViewModelMaxCol)
        let itemH = (self.frame.height - 25) / CGFloat(CZEmoticonKeyBoardViewModelMaxRow)

        for (index,value) in emoticonsArray.enumerate() {
            //根据index和value计算对应的x,和y值
            let col = index % CZEmoticonKeyBoardViewModelMaxCol
            let row = index / CZEmoticonKeyBoardViewModelMaxCol
            //设置位置
            let itemX = CGFloat(col) * itemW
            let itemY = CGFloat(row) * itemH
            //计算对应的cell的位置
            value.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
            
        }
        //设置删除按钮的位置
        let buttonX = self.frame.width - itemW
        let buttonY = self.frame.height - itemH - 25
        
        deleteButton.frame = CGRect(x: buttonX, y: buttonY, width: itemW, height: itemH)
    }
    //懒加载删除按钮
    private lazy var deleteButton: UIButton = {
       let button = UIButton()
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        button.addTarget(self, action: "didClickDeleteButton:", forControlEvents: .TouchUpInside)
        
        return button
    }()
    @objc private func didClickDeleteButton(button: UIButton){
        
        
        //由于是多层之间的传送,所以需要使用的是消息
//        NSNotificationCenter.defaultCenter().postNotification(CZDeleteButtonNotification)
        NSNotificationCenter.defaultCenter().postNotificationName(CZDeleteButtonNotification, object: nil)
        
        
    }
    
//    //创建一个label
//    private lazy var label: UILabel = UILabel(textColor: UIColor.blackColor(), fontSize: 45)
    
    private lazy var messageLabel: UILabel = {
       let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 12)
        label.text = "最近使用的表情"
        return label
    }()
    //懒加载一个popView
    private lazy var popView: CZEmoticonPopView = CZEmoticonPopView.popView()
}
